package com.zy.kotlinbaselibrary.net

import com.zy.kotlinbaselibrary.log.XLog
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import org.json.JSONObject

class DataEntityInterceptor: Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        // 请求之前调用
        val request = chain.request()

        // 请求之后调用
        val response = chain.proceed(request)

        return dataResponse(response)
    }

    private fun dataResponse(response: Response): Response {

        val builder = response.newBuilder()
        val clone = builder.build()
        var body = clone.body
        val mediaType = body?.contentType()

        XLog.i("body:${body}")

        var jsonObject = JSONObject()
        jsonObject.put("code", clone.code)
        jsonObject.put("message", "请求")

        if(body == null){
            jsonObject.put("data", null)
        }else{
            var string = body.string()
            var temp = JSONObject(string)
            jsonObject.put("data",temp)
        }


        XLog.i("JSONOBJECT:${jsonObject.toString()}")


        body = ResponseBody.create(mediaType, jsonObject.toString())
        return response.newBuilder().body(body).build()


    }
}